package com.gray.file.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

@Controller
public class FileUploadController {

    /*文件上传下载路径*/
    private String path = "d:\\idea_project\\";
    /*当前可下载文件名*/
    private String fileName = null;

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        //获取文件的名字
        this.fileName = file.getOriginalFilename();
        //获取文件后缀名
//        String suffix = filename.substring(filename.lastIndexOf("."));
        //防止文件名重复  随机文件名
//        filename = UUID.randomUUID() + suffix;

        String filename = path +  this.fileName;
        File f = new File(filename);
        //如果D盘下没有upload文件夹 则创建一个
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        try {
            //把MultipartFile转化为File类型
            file.transferTo(f);
            return "success";
        } catch (IOException e) {
            e.printStackTrace();
            return "error";
        }
    }

    /**
     * 先上传一个文件，记录名称。点击下载，可下载
     * @param response
     * @return
     */
    @RequestMapping("/download")
    public String download(HttpServletResponse response) {
        try {
            // 文件地址，真实环境是存放在数据库中的
            File file = new File(path + fileName);
            // 创建输入流，传入文件对象
            FileInputStream fis = new FileInputStream(file);
            // 设置相关格式
            response.setContentType("application/force-download");
            // 设置下载后的文件名以及header
            String fileName = URLEncoder.encode(this.fileName,"UTF-8");
            response.addHeader("Content-disposition", "attachment;filename=" + fileName);
            OutputStream os = response.getOutputStream();
            // 常规操作
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = fis.read(buf)) != -1) {
                os.write(buf, 0, len);
            }
            os.close();
            fis.close();
            return "success";       //为了测试方便  我写了两个html  一个是success.html还有一个是error.html  用来表示成功还是失败
        } catch (IOException e) {
            e.printStackTrace();
            return "error";
        }
    }

    //当请求localhost:8080的时候 默认跳转到index.html页面
    @RequestMapping("/file01")
    public ModelAndView index() {
        return new ModelAndView("file01");
    }
}